﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Collections.Generic;

using SBPweb.Forge.Contracts.Extensibility;

using SBPweb.Communication.Shared.Library;

using SBPweb.Communication.Client.Library.Xmpp;
using SBPweb.Communication.Client.Library.Xmpp.Configuration;
using SBPweb.Communication.Client.Library.Xmpp.Conversations;

using SBPweb.Communication.Client.Controls.Xmpp.Themes;

namespace SBPweb.Communication.Client.Presentation.Silverlight
{

    public partial class App : Application, IExtendable
    {

        #region Private fields

        private Dictionary<string, object> dictProperties = new Dictionary<string, object>();
        private MessengerBase messenger = new Messenger();

        #endregion

        #region Constructor logic

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            Put<MessengerBase>("Messenger", messenger);

            InitializeComponent();
            //TODO: SL3
#if SL3
            Resources.MergedDictionaries.Add(Generic.Instance);
#endif

            messenger.Initialized += new EventHandler(messenger_Initialized);
        }

        #endregion

        #region Property accessors

        public MessengerBase Messenger
        {
            get
            {
                return messenger;
            }
        }

        #endregion

        #region Methods

        #region Event handlers

        private void messenger_Initialized(object sender, EventArgs e)
        {
            //string userName = "test001";
            string userName = HtmlPage.Window.Prompt("What username would you like to sign in with?");
            messenger.Connections.Connect(userName, "a");
        }

        private void messenger_Conversations_FindPublicConferencesReceived(object sender, EventArgs e)
        {
            //messenger.Conversations.OpenConference("coop_test");
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new Pages.Main();

            (messenger.Configurations as ConfigurationManager).Parameters = e.InitParams;
            (messenger.Conversations as ConversationManager).FindPublicConferencesReceived += new EventHandler(messenger_Conversations_FindPublicConferencesReceived);
            messenger.Initialize();
        }

        private void Application_Exit(object sender, EventArgs e)
        {
            messenger.Terminate();
        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }

        #endregion

        #region Extensibility

        public T Get<T>(string propertyName)
        {
            return (T)dictProperties[propertyName];
        }

        public void Put<T>(string propertyName, T value)
        {
            dictProperties[propertyName] = value;
        }

        #endregion

        #endregion

    }

}